
const _interopRequireDefault = require('@babel/runtime/helpers/interopRequireDefault');

exports.__esModule = true;
exports.updateOverlay = updateOverlay;
exports.openOverlay = openOverlay;
exports.closeOverlay = closeOverlay;

const _extends2 = _interopRequireDefault(require('@babel/runtime/helpers/extends'));

const _overlay = _interopRequireDefault(require('../../overlay'));

const _context = require('./context');

const _functional = require('../../utils/functional');

const defaultConfig = {
  className: '',
  customStyle: {},
};
let overlay; // close popup when click overlay && closeOnClickOverlay is true

function onClickOverlay() {
  if (_context.context.top) {
    const { vm } = _context.context.top;
    vm.$emit('click-overlay');

    if (vm.closeOnClickOverlay) {
      if (vm.onClickOverlay) {
        vm.onClickOverlay();
      } else {
        vm.close();
      }
    }
  }
}

function mountOverlay() {
  overlay = (0, _functional.mount)(_overlay.default, {
    on: {
      click: onClickOverlay,
    },
  });
}

function updateOverlay() {
  if (!overlay) {
    mountOverlay();
  }

  if (_context.context.top) {
    const _context$top = _context.context.top;
    const { vm } = _context$top;
    const { config } = _context$top;
    const el = vm.$el;

    if (el && el.parentNode) {
      el.parentNode.insertBefore(overlay.$el, el);
    } else {
      document.body.appendChild(overlay.$el);
    }

    (0, _extends2.default)(overlay, defaultConfig, config, {
      show: true,
    });
  } else {
    overlay.show = false;
  }
}

function openOverlay(vm, config) {
  if (!_context.context.stack.some((item) => item.vm === vm)) {
    _context.context.stack.push({
      vm,
      config,
    });

    updateOverlay();
  }
}

function closeOverlay(vm) {
  const { stack } = _context.context;

  if (stack.length) {
    if (_context.context.top.vm === vm) {
      stack.pop();
      updateOverlay();
    } else {
      _context.context.stack = stack.filter((item) => item.vm !== vm);
    }
  }
}
